"""
初始化脚本 - 创建数据库和默认数据
"""
import os
import sys
from pathlib import Path

# 添加项目路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from core.config import get_settings
from core.database import create_tables, SessionLocal
from models.database import User, SystemConfig, ParseTask, ParseResult, SliceTask, SliceChunk, APILog, TokenBlacklist
from core.auth import get_password_hash

settings = get_settings()



def create_directories():
    """创建必要的目录"""
    directories = [
        settings.upload_dir,
        settings.parsed_results_dir,
        "logs",
        "logs/tasks",
        "logs/api",
        "static",
        "static/css",
        "static/js",
        "static/images"
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
        print(f"创建目录: {directory}")


def main():
    """主函数"""
    print("开始初始化MinerU文档解析系统...")
    
    try:
        # 创建目录
        print("\n1. 创建目录结构...")
        create_directories()
        
        # 创建数据库表
        print("\n2. 创建数据库表...")
        create_tables()
        
        # 创建管理员用户和系统配置
        print("\n3. 创建默认数据...")
        db = SessionLocal()
        try:
            # 检查是否已存在管理员用户
            admin_user = db.query(User).filter(User.username == "admin").first()
            if not admin_user:
                admin_user = User(
                    username="admin",
                    email="admin@system.com",
                    password_hash=get_password_hash(settings.default_admin_password),
                    role="admin",
                    is_active=True
                )
                db.add(admin_user)
                print(f"默认管理员用户已创建：admin/{settings.default_admin_password}")
            else:
                print("管理员用户已存在")
            
            # 创建系统配置
            configs = [
                {"key": "jwt_expire_seconds", "value": "3600", "desc": "JWT令牌过期时间（秒）"},
                {"key": "max_file_size", "value": "52428800", "desc": "最大文件大小（字节）"},
                {"key": "max_concurrent_tasks", "value": "10", "desc": "最大并发任务数"},
                {"key": "task_timeout_seconds", "value": "300", "desc": "任务超时时间（秒）"},
                {"key": "default_ocr_engine", "value": "paddle", "desc": "默认OCR引擎"},
                {"key": "results_retention_days", "value": "90", "desc": "结果保留天数"}
            ]
            
            for config in configs:
                existing_config = db.query(SystemConfig).filter(SystemConfig.config_key == config["key"]).first()
                if not existing_config:
                    new_config = SystemConfig(
                        config_key=config["key"],
                        config_value=config["value"],
                        description=config["desc"]
                    )
                    db.add(new_config)
            
            db.commit()
            print("系统配置已创建")
            
        except Exception as e:
            db.rollback()
            raise e
        finally:
            db.close()
        
        print("\n系统初始化完成！")
        print("\n重要信息:")
        print(f"  - 默认管理员账号: admin / {settings.default_admin_password}")
        print("  - 数据库文件: app.db")
        print("  - 上传目录: uploads/")
        print("  - 解析结果目录: parsed_results/")
        print("  - 日志目录: logs/")
        print("\n启动服务:")
        print("  - API服务: python main.py")
        print("  - MCP服务: python mcp_server/server.py")
        
    except Exception as e:
        print(f"\n初始化失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()